package com.aek.aekdroid;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.aek.aekdroid.help.TabHelpActivity;

public abstract class BaseActivity extends Activity {
	protected AekDroidApplication aek;
	public static final String TAG = "BaseActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		aek = (AekDroidApplication) getApplication();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (item.getItemId() == R.id.menu_schedule) {
			MyLog.d(TAG, "Calling menu Schedule");
			startActivity(new Intent(this, ScheduleActivity.class));
		} else if (item.getItemId() == R.id.menu_preferences) {
			MyLog.d(TAG, "Calling menu Preferences");
			startActivity(new Intent(this, PrefsActivity.class));
		} else if (item.getItemId() == R.id.menu_update) {
			MyLog.d(TAG, "Calling menu Update");
			Toast.makeText(this, R.string.toastUpdating, Toast.LENGTH_SHORT).show();
			Helper.updateNow(this);
		} else if (item.getItemId() == R.id.menu_purge) {
			MyLog.d(TAG, "Calling menu Purge");
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getString(R.string.confirmPurge)).setCancelable(false)
					.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
							Calendar c = new Calendar(BaseActivity.this);
							c.deleteCalendar(aek);
							int matches = aek.getMatchData().purge();
							if (matches == -1) {
								Toast.makeText(BaseActivity.this, getString(R.string.dbPurgeFailed), Toast.LENGTH_LONG).show();
							} else {
								Toast.makeText(BaseActivity.this, getString(R.string.dbPurgeSucceeded, matches), Toast.LENGTH_LONG).show();
								BaseActivity.this.startActivity(new Intent(BaseActivity.this, ScheduleActivity.class));
							}

						}
					}).setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			AlertDialog alert = builder.show();
		} else if (item.getItemId() == R.id.menu_help) {
			MyLog.d(TAG, "Calling menu Help");
			startActivity(new Intent(this, TabHelpActivity.class));
		} else if (item.getItemId() == R.id.menu_checkUpdate) {
			MyLog.d(TAG, "Calling menu Check");
			Intent checkUpdate = new Intent(this, UpdateChecker.class);
			checkUpdate.putExtra("manual", true);
			startService(checkUpdate);
		}
		return true;
	}
}
